import config from '@/config';
import storage from '@/utils/storage';
import constant from '@/utils/constant';
import { login, logout, getInfo, getCodeImg } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';

const baseUrl = config.baseUrl;
const defaultConsignor = storage.get(constant.SYS_CONSIGNOR) || {};
const defaultAvatar = defaultConsignor.avatarFileNo
  ? defaultConsignor.avatarFileNo[0]
  : {};
const user = {
  state: {
    token: getToken(),
    consignor: defaultConsignor,
    avatar: defaultAvatar
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_CONSIGNOR: (state, consignor) => {
      state.consignor = consignor || {};
      storage.set(constant.SYS_CONSIGNOR, consignor);
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar || {};
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password.trim();
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((res) => {
            setToken(res.token);
            commit('SET_TOKEN', res.token);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
        // let teken = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyaWQiOjEsImxvZ2luX3VzZXJfa2V5IjoiZmY5ODkwNjQtNmEwZi00YjA0LTllYTktNjQ2OTlkOTZiZWRiIn0.LH5eO6kZnA3TFqbvtnbaKJP76znYKV3jl4Yoi1-h1D-B1fA_75mdGMygFEXlP_A_HPV0g69IYHZ5Ogfymx9oXQ"
      });
    },
    // 获取code
    GetCode({ commit, state }) {
      return new Promise((resolve, reject) => {
        getCodeImg()
          .then((res) => {
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            // uni.setStorageSync('nyj_app_user_id', res.data.sysUser.userId);
            commit('SET_CONSIGNOR', res.data);
            commit(
              'SET_AVATAR',
              res.data.sysUser.avatar ? res.data.sysUser.avatar : state.avatar
            );
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            storage.clean();
            // commit('SET_CONSIGNOR', '');
            commit('SET_AVATAR', '');
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    }
  }
};

export default user;
